import tkinter as tk
import ttkbootstrap as ttkb
from ttkbootstrap.constants import *
import os
import markdown
from PIL import Image, ImageTk
from tkinterdnd2 import TkinterDnD
import tkinter.filedialog as filedialog
from tkinterweb import HtmlFrame
from views import ImportView, CustomMessageBox

from .exam_statistics import ExamStatisticsView
from .questions_bank_view import QuestionsBankView

from utils import resource_path, log_exception, log_info, log_debug
from dao import clear_user_data
from app_state import app_state
from configs import WINDOW_CONFIG

class SettingsView(tk.Toplevel, TkinterDnD.DnDWrapper):
    def __init__(self, parent, app_instance, practice_service):
        super().__init__(parent)
        self.parent = parent
        self.app = app_instance
        self.practice_service = practice_service
        self.title("系统设置")
        width = WINDOW_CONFIG['settings']['width']
        height = WINDOW_CONFIG['settings']['height']
        self.geometry(f"{width}x{height}")
        # 先隐藏窗口，避免快速开闭
        self.withdraw()
        
        self.transient(parent)
        self.grab_set()
        self.focus_set()
        
        # 使窗口在主窗口中央弹出
        self.update_idletasks()  # 确保窗口尺寸已计算
        width = self.winfo_width()
        height = self.winfo_height()
        x = parent.winfo_x() + (parent.winfo_width() // 2) - (width // 2)
        y = parent.winfo_y() + (parent.winfo_height() // 2) - (height // 2)
        self.geometry(f"+{x}+{y}")
        
        # 设置应用图标
        icon_path = resource_path(os.path.join('icon', 'icon.ico'))
        if os.path.exists(icon_path):
            self.iconbitmap(icon_path)

        # 初始化DnD功能
        self.TkdndVersion = TkinterDnD._require(self)

        self.filedialog = filedialog

        # 创建主框架
        self.main_frame = ttkb.Frame(self)
        self.main_frame.pack(fill=tk.BOTH, expand=True)

        # 导航菜单项
        self.menu_items = [
            ("导入题库", "import.png", self.show_import_settings),
            ("考试统计", "statistics.png", self.show_exam_statistics),
            ("进度管理", "clear_process.png", self.show_progress_management),
            ("数据清理", "clean_data.png", self.show_data_cleanup),
            ("题库管理", "questions_bank.png", self.show_questions_bank),
            ("关于", "user.png", self.show_about)  # 使用user.png作为临时图标
        ]

        # 创建左侧导航菜单
        self.create_navigation_menu()

        # 创建右侧内容区域
        self.content_frame = ttkb.Frame(self.main_frame)
        self.content_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=5, pady=5)

        # 默认显示导入设置
        self.show_import_settings()
        # 默认选中第一个菜单项
        if hasattr(self, 'menu_frames') and self.menu_frames:
            self.update_selected_menu(self.menu_frames[0])

        # 确保所有窗口元素都已创建
        self.update_idletasks()
        
        # 添加一个短暂延迟后显示窗口，避免闪烁
        self.after(100, self.deiconify)

    def create_navigation_menu(self):
        # 创建导航框架，使用与主窗口solar主题一致的背景色
        nav_frame = ttkb.Frame(self.main_frame, bootstyle="solar", width=150)
        nav_frame.pack(side=tk.LEFT, fill=tk.Y, padx=5, pady=5)

        # 添加导航区与功能区之间的间隔竖线，使用比背景色深一点的颜色
        separator = ttkb.Separator(self.main_frame, orient=tk.VERTICAL, bootstyle="solar-tertiary")
        separator.pack(side=tk.LEFT, fill=tk.Y, padx=2)

        # 设置字体
        font = ("SimHei", 12)

        # 初始化当前选中的菜单项
        self.current_menu_item = None

        # 初始化菜单框架列表
        self.menu_frames = []

        # 创建菜单项按钮
        for i, (text, icon_name, command) in enumerate(self.menu_items):
            # 创建按钮框架
            btn_frame = ttkb.Frame(nav_frame, bootstyle="solar")
            btn_frame.pack(fill=tk.X, pady=2, padx=5)
            # 确保按钮框架和标签都能触发选中状态更新
            btn_frame.bind("<Button-1>", lambda e, c=command, f=btn_frame: [self.update_selected_menu(f), c()])
            btn_frame.configure(cursor="hand2")
            self.menu_frames.append(btn_frame)
            
            # 加载图标
            icon_path = resource_path(os.path.join("icon", icon_name))
            if os.path.exists(icon_path):
                icon_img = Image.open(icon_path)
                icon_img = icon_img.resize((20, 20), Image.Resampling.LANCZOS)
                icon_photo = ImageTk.PhotoImage(icon_img)
            else:
                icon_photo = None

            # 创建按钮（使用Label模拟按钮）
            btn = ttkb.Label(
                btn_frame,
                text=text,
                image=icon_photo,
                compound=tk.LEFT,
                font=font,
                foreground="white",
                bootstyle="solar"
            )
            btn.pack(fill=tk.BOTH, expand=True, padx=0, pady=5)
            btn.image = icon_photo  # 保持引用

            # 添加鼠标悬停效果 - 确保背景覆盖整个区域
            # 确保btn已经被完全定义
            def on_enter(e, frame=btn_frame, btn_ref=btn):
                if frame != self.current_menu_item:
                    btn_ref.configure(foreground="#1194d9")
            
            def on_leave(e, frame=btn_frame, btn_ref=btn):
                if frame != self.current_menu_item:
                    btn_ref.configure(foreground="white")
            
            
            btn_frame.bind("<Enter>", on_enter)
            btn_frame.bind("<Leave>", on_leave)
            # 确保点击标签也能更新选中状态
            btn.bind("<Button-1>", lambda e, c=command, f=btn_frame: [self.update_selected_menu(f), c()])
            btn.configure(cursor="hand2")

            # 在每个菜单项之间添加分隔线（最后一个除外）
            if i < len(self.menu_items) - 1:
                separator = ttkb.Separator(nav_frame, orient=tk.HORIZONTAL, bootstyle="solar-tertiary")
                separator.pack(fill=tk.X, padx=5, pady=1)

    def update_selected_menu(self, frame):
        # 更新当前选中的菜单项
        if self.current_menu_item:
            self.current_menu_item.configure(bootstyle="solar", borderwidth=0)
            for child in self.current_menu_item.winfo_children():
                if isinstance(child, ttkb.Label):
                    child.configure(foreground="white")

        self.current_menu_item = frame
        # 使用dark样式表示选中状态（对应#303745类似的深色背景）
        # frame.configure(bootstyle="dark", borderwidth=0)
        for child in frame.winfo_children():
            if isinstance(child, ttkb.Label):
                child.configure(foreground="#1194d9")

    def clear_content_frame(self):
        # 清除内容区域
        for widget in self.content_frame.winfo_children():
            widget.destroy()

    def show_import_settings(self):
        self.clear_content_frame()

        # 创建导入视图
        self.import_view = ImportView(
            self.content_frame
        )
        self.import_view.pack(fill=tk.BOTH, expand=True)

    def show_exam_statistics(self):
        # 高亮当前菜单项
        for i, (text, _, _) in enumerate(self.menu_items):
            if text == "考试统计":
                self.update_selected_menu(self.menu_frames[i])
                break
        self.clear_content_frame()

        # 调用主应用中的考试统计功能
        # 创建一个框架来放置统计内容
        stats_frame = ttkb.Frame(self.content_frame)
        stats_frame.pack(fill=tk.BOTH, expand=True)

        stats_view = ExamStatisticsView(font = ("SimHei", 12))
        stats_view.view_in_frame(stats_frame, app_state.current_user_id, self)

    def show_progress_management(self):
        # 高亮当前菜单项
        for i, (text, _, _) in enumerate(self.menu_items):
            if text == "进度管理":
                self.update_selected_menu(self.menu_frames[i])
                break
        self.clear_content_frame()

        # 标题
        title_label = ttkb.Label(
            self.content_frame,
            text="进度管理",
            font=("SimHei", 16, "bold"),
            bootstyle="primary"
        )
        title_label.pack(pady=10)

        # 重置练习进度
        reset_frame = ttkb.LabelFrame(self.content_frame, text="重置练习进度", bootstyle="info")
        reset_frame.pack(fill=tk.X, pady=10, padx=10)

        # 类别选择
        ttkb.Label(reset_frame, text="选择类别:").pack(pady=5)
        category_var = tk.StringVar(value="all")

        ttkb.Radiobutton(reset_frame, text="全部类别", variable=category_var, value="all").pack(anchor=tk.W, padx=10)
        ttkb.Radiobutton(reset_frame, text="A类", variable=category_var, value="A").pack(anchor=tk.W, padx=10)
        ttkb.Radiobutton(reset_frame, text="B类", variable=category_var, value="B").pack(anchor=tk.W, padx=10)
        ttkb.Radiobutton(reset_frame, text="C类", variable=category_var, value="C").pack(anchor=tk.W, padx=10)

        # 重置按钮
        def reset_progress():
            category = category_var.get()
            if category == "all":
                categories = ['A', 'B', 'C']
            else:
                categories = [category]

            for cat in categories:
                # 保存进度为0来重置练习进度
                self.practice_service.save_practice_progress(app_state.current_user_id, cat, 0)
                app_state.practice_progress[cat] = 0

            CustomMessageBox.showinfo("成功", "练习进度已重置", parent=self)  # 已正确使用self作为父窗口

        reset_btn = ttkb.Button(
            reset_frame,
            text="重置进度",
            bootstyle="danger",
            command=reset_progress
        )
        reset_btn.pack(pady=10)

    def clear_all_user_data(self):
        # 显示确认对话框
        current_user_id = app_state.current_user_id
        if current_user_id:
            # 添加日志输出
            log_debug(f"准备清空用户 {current_user_id} 的所有数据，包括收藏本")
            # 调用数据库方法清空当前用户数据
            log_debug(f"正在清空用户 {current_user_id} 的数据")
            clear_user_data(current_user_id)

            log_debug(f"用户 {current_user_id} 的数据已清空")
            # 重置AppState中的练习进度
            app_state.reset_practice_progress()
            # 显示成功消息
            CustomMessageBox.showinfo("提示", "当前用户的数据已清空。", parent=self)
        else:
            CustomMessageBox.showinfo("提示", "请先登录再执行此操作。", parent=self)

    def show_data_cleanup(self):
        # 高亮当前菜单项
        for i, (text, _, _) in enumerate(self.menu_items):
            if text == "数据清理":
                self.update_selected_menu(self.menu_frames[i])
                break
        self.clear_content_frame()

        # 标题
        title_label = ttkb.Label(
            self.content_frame,
            text="数据清理",
            font=('SimHei', 16, 'bold'),
            bootstyle="primary"
        )
        title_label.pack(pady=10)

        # 清空用户数据
        clear_frame = ttkb.LabelFrame(self.content_frame, text="清空用户数据", bootstyle="info")
        clear_frame.pack(fill=tk.X, pady=10, padx=10)

        ttkb.Label(clear_frame, text="警告: 此操作将清空所有用户数据，包括练习进度、错题本和收藏夹！").pack(pady=10)

        # 确认按钮
        def confirm_clear():
            if CustomMessageBox.askyesno("确认", "确定要清空所有数据吗？此操作不可恢复！", parent=self):
                self.clear_all_user_data()

        clear_btn = ttkb.Button(
            clear_frame,
            text="清空数据",
            bootstyle="danger",
            command=confirm_clear
        )
        clear_btn.pack(pady=10)

    def show_questions_bank(self):
        # 高亮当前菜单项
        for i, (text, _, _) in enumerate(self.menu_items):
            if text == "题库管理":
                self.update_selected_menu(self.menu_frames[i])
                break
        self.clear_content_frame()

        # 创建题库管理框架
        bank_frame = ttkb.Frame(self.content_frame)
        bank_frame.pack(fill=tk.BOTH, expand=True)

        # 创建题库管理实例
        self.bank_app = QuestionsBankView(bank_frame)

    def show_about(self):
        # 高亮当前菜单项
        for i, (text, _, _) in enumerate(self.menu_items):
            if text == "关于":
                self.update_selected_menu(self.menu_frames[i])
                break
        self.clear_content_frame()

        # 创建Web视图区域
        web_frame = ttkb.Frame(self.content_frame)
        web_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        
        # 创建HtmlFrame来显示HTML内容，完全禁用水平滚动条
        # 只使用HtmlFrame支持的参数
        html_frame = HtmlFrame(
            web_frame, 
            horizontal_scrollbar="auto", 
            vertical_scrollbar="auto",
            messages_enabled=False
        )
        html_frame.pack(fill=tk.BOTH, expand=True)
        
        # 使用与settings_view.py窗口相同的背景色
        # 直接设置为透明背景色，让内容区域背景色与主窗口保持一致
        parent_bg = "transparent"
        
        # 由于ttkbootstrap组件特性，我们需要通过特殊方式确保背景色一致
        # 1. 尝试获取content_frame的实际背景色
        try:
            # 对于ttkbootstrap组件，可以通过这种方式获取背景色
            if hasattr(self.content_frame, '_w'):
                parent_bg = self.content_frame.tk.eval(f"ttk::style lookup {self.content_frame.winfo_class()} -background")
        except:
            # 如果获取失败，保持透明背景
            parent_bg = "transparent"
        
        # 读取并显示README.md内容
        # 使用utils中的resource_path函数获取文件路径，确保打包后也能正确访问
        readme_path = resource_path('README.md')
        with open(readme_path, 'r', encoding='utf-8') as f:
            readme_content = f.read()
        
        # 使用markdown库将markdown转换为HTML，启用nl2br扩展确保换行符被正确处理
        html_content = markdown.markdown(readme_content, extensions=['nl2br'])
        # log_debug(f"html_content: {html_content}")
        # 构建简单但有效的HTML内容，确保背景色一致且无水平滚动条
        styled_html = f"""
        <html>
        <head>
            <meta charset="UTF-8">
            <style>
                /* 重置所有样式并强制背景色和禁止水平滚动 */
                * {{
                    margin: 0 !important;
                    padding: 0 !important;
                    border: 0 !important;
                    outline: 0 !important;
                    font-size: 100% !important;
                    vertical-align: baseline !important;
                    background: transparent !important;
                    color: inherit !important;
                    box-sizing: border-box !important;
                    max-width: 98% !important; /* 比100%略小以确保没有溢出 */
                    overflow-x: hidden !important;
                    float: none !important;
                    position: static !important;
                }}
                
                /* 特殊元素处理 - 彻底禁止水平滚动 */
                html {{
                    overflow-x: hidden !important;
                    width: 98% !important;
                    max-width: 98% !important;
                }}
                
                body {{
                    background-color: {parent_bg} !important;
                    color: #ffffff !important;
                    font-family: SimHei, Arial, sans-serif !important;
                    line-height: 1.6 !important;
                    padding: 10px !important;
                    margin: 0 !important;
                    width: 98% !important;
                    max-width: 98% !important;
                    overflow-x: hidden !important;
                    position: relative !important;
                }}
                
                /* 内容元素样式 */
                h1 {{ 
                    color: #1194d9 !important; 
                    margin: 20px 0 15px !important;
                    max-width: 98% !important;
                    overflow-x: hidden !important;
                    display: block !important;
                    font-size: 24px !important; /* 最大字体 */
                    font-weight: bold !important;
                }}
                h2 {{ 
                    color: #1194d9 !important; 
                    margin: 18px 0 12px !important;
                    max-width: 98% !important;
                    overflow-x: hidden !important;
                    display: block !important;
                    font-size: 20px !important; /* 中等字体 */
                    font-weight: bold !important;
                }}
                h3 {{ 
                    color: #1194d9 !important; 
                    margin: 15px 0 10px !important;
                    max-width: 98% !important;
                    overflow-x: hidden !important;
                    display: block !important;
                    font-size: 16px !important; /* 较小字体 */
                    font-weight: 600 !important;
                }}
                p {{ 
                    margin-bottom: 10px !important;
                    word-wrap: break-word !important;
                    white-space: normal !important;
                    overflow-x: hidden !important;
                    max-width: 98% !important;
                    display: block !important;
                }}
                li {{ 
                    margin-bottom: 10px !important;
                    word-wrap: break-word !important;
                    white-space: normal !important;
                    overflow-x: hidden !important;
                    max-width: 98% !important;
                    display: list-item !important; /* 确保列表项显示为列表项类型 */
                    list-style-position: outside !important;
                }}
                ul {{ 
                    padding-left: 25px !important; 
                    margin-bottom: 15px !important;
                    max-width: 98% !important;
                    overflow-x: hidden !important;
                    display: block !important;
                    list-style-type: disc !important; /* 无序列表样式 */
                }}
                ol {{ 
                    padding-left: 25px !important; 
                    margin-bottom: 15px !important;
                    max-width: 98% !important;
                    overflow-x: hidden !important;
                    display: block !important;
                    list-style-type: decimal !important; /* 确保有序列表显示数字序号 */
                }}
                
                /* 内联元素特殊处理 - 防止额外换行 */
                strong, b, em, i, span, code {{ 
                    display: inline !important; 
                    max-width: 100% !important;
                    margin: 0 !important;
                    padding: 0 !important;
                }}
                
                /* 内联code样式 - 保持内联显示 */
                code {{ 
                    font-family: 'Courier New', monospace !important;
                    background-color: transparent !important;
                    color: inherit !important;
                    padding: 2px 4px !important;
                    border-radius: 3px !important;
                    display: inline !important;
                    margin: 0 !important;
                    line-height: 1.0 !important;
                }}
                
                /* 代码块样式 - 修复多余换行问题并确保不导致水平滚动 */
                pre {{ 
                    font-family: 'Courier New', monospace !important;
                    background-color: transparent !important;
                    color: inherit !important;
                    padding: 10px !important;
                    margin: 8px 0 5px 0 !important; /* 进一步减少下边距 */
                    border: none !important;
                    white-space: pre-wrap !important;
                    word-wrap: break-word !important;
                    word-break: break-all !important;
                    overflow-x: hidden !important;
                    max-width: 98% !important;
                    width: 98% !important;
                    display: block !important;
                    line-height: 1.1 !important; /* 进一步减少行高 */
                    position: relative !important;
                }}
                
                pre::after {{ 
                    content: '' !important;
                    display: block !important;
                    height: 0 !important;
                    clear: both !important;
                    overflow: hidden !important;
                }}
                
                /* 图片和链接样式 - 确保图片不会导致水平滚动 */
                img {{ 
                    max-width: 95% !important; 
                    height: auto !important;
                    display: block !important; 
                    margin: 10px auto !important; /* 减少上下边距 */
                    width: auto !important;
                    overflow-x: hidden !important;
                }}
                
                /* 链接样式 */
                a {{ 
                    color: #0000ff !important;
                    text-decoration: underline !important;
                    display: inline !important; /* 保持链接为内联元素 */
                    max-width: 100% !important;
                }}
                
                /* 其他可能导致滚动的元素 */
                table, th, td {{
                    max-width: 98% !important;
                    width: auto !important;
                    overflow-x: hidden !important;
                    white-space: normal !important;
                    display: block !important;
                }}
                
                /* 确保所有元素都不会产生水平滚动条 */
                *:not(body):not(html) {{ 
                    overflow-x: hidden !important;
                    max-width: inherit !important;
                }}
                
                /* 特别针对滚动条的控制 - 更严格的规则 */
                ::-webkit-scrollbar, ::-webkit-scrollbar-track, ::-webkit-scrollbar-thumb, ::-webkit-scrollbar-corner {{ 
                    display: none !important;
                    width: 0 !important;
                    height: 0 !important;
                    background: transparent !important;
                }}
                
                html, body, .scroll-container, .scroll-wrapper {{ 
                    -ms-overflow-style: none !important;
                    scrollbar-width: none !important;
                    overflow-x: hidden !important;
                    overflow-y: auto !important;
                }}
                
                /* 确保Web视图容器也不会显示滚动条 */
                .web-view-container, .web-content, #web-view {{ 
                    overflow-x: hidden !important;
                    overflow-y: auto !important;
                    -ms-overflow-style: none !important;
                    scrollbar-width: none !important;
                }}
            </style>
        </head>
        <body>
            {html_content}
        </body>
        </html>
        """
        
        # 加载HTML内容
        html_frame.load_html(styled_html)
